/*
 * Class to parse KML input from google into data easily usable by application.
 */
package com.kmlparser;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;

import com.google.android.maps.GeoPoint;

public class KMLParser {
    static final String kmlURL = "http://maps.google.com/maps?q=";
    static final String kmlFROM = "from+";
    static final String kmlTO = "+to+";
    static final String kmlOUTPUT = "&output=kml";
    String geoCode1;
    String geoCode2;
    String inputLine = "";
    String receivedLine = "";
    String tempString = "";
    String rawDistance = "";
	String fromLocation = "";
    String toLocation = "";
    String kmlPoints = "";
    String kmlPointsArray[];
    String startEndAddresses[];
    String tempPoint[];
    String startAddress;
    String endAddress;


    /**
     * @param args the command line arguments
     */
    public KMLParser(){

    }

    public KMLParser(String startGeoCode, String endGeoCode){
	getDistance(new String[]{startGeoCode,endGeoCode});
    }

    public String getDistance(String [] args) {
	// http://maps.google.com/maps/geo?q=1.3706068,103.8523412&output=xml&sensor=true&key=ABQIAAAAAfTrMR10sETLehmY9-wPYhSqJZCNvwQdu8l_Rs8QCtDYvtsJ1xT37bZY1I5SPlyI6oQBQqxwC3-FRA


	int argsCount;
	argsCount = args.length;
	if (argsCount == 2)
	{
	    System.out.println("Parsing 2 values");
	    geoCode1 = args[0];
	    geoCode2 = args[1];
	    System.out.println("Building query from data");
	    String googleKML = kmlBuilder(geoCode1, geoCode2);
	    System.out.println("Connecting to " + googleKML);
	    try {
		URL url = new URL(googleKML);
		BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
		while ((inputLine = in.readLine()) != null) {
		    System.out.println(inputLine);
		    receivedLine = inputLine;
		    if (inputLine.contains("<![CDATA[Distance:")) {
			tempString = inputLine.substring(inputLine.indexOf("<name>") + 6, inputLine.indexOf("</name>"));
			startEndAddresses = tempString.split(" to ");
			tempString = inputLine.substring(inputLine.indexOf("<![CDATA[Distance:") + 19, inputLine.lastIndexOf("&#160;") + 8);
			tempString = tempString.replace("&#160;", "");
			rawDistance = tempString;
			System.out.println("Your trip is estimated at " + rawDistance + " by car.");
			System.out.println("Start Location: " + startEndAddresses[0] + " (" + geoCode1 + ")");
			startAddress = startEndAddresses[0];
			System.out.println("End Location: " + startEndAddresses[1] + " (" + geoCode2 + ")");
			endAddress = startEndAddresses[1];
			tempString = inputLine.substring(inputLine.indexOf("<LineString><coordinates>")+25, inputLine.indexOf(" </coordinates></LineString>"));
			kmlPoints = tempString.replace(",0.000000", "");
			kmlPointsArray = kmlPoints.split(" "); 
			return "Travel Distance : " + rawDistance + "\nStart Location: " + startEndAddresses[0] + " (" + geoCode1 + ")" + "\nEnd Location: " + startEndAddresses[1] + " (" + geoCode2 + ")";
		    }
		}
	    } catch (Exception e) {
		e.printStackTrace();
		return "error";
	    }
	}
	else
	{
	    return "error";
	    //System.out.println("Incorrect input. Please provide 2 LatLng values separated by a space.");
	    //System.exit(0);
	}
	return "error";
    }

    public String getDistance(int geopointALat, int geopointALng, int geopointBLat, int geopointBLng) {
	// http://maps.google.com/maps/geo?q=1.3706068,103.8523412&output=xml&sensor=true&key=ABQIAAAAAfTrMR10sETLehmY9-wPYhSqJZCNvwQdu8l_Rs8QCtDYvtsJ1xT37bZY1I5SPlyI6oQBQqxwC3-FRA
	geoCode1 = Double.toString(geopointALat / 1E6) + "," + Double.toString(geopointALng / 1E6);
	geoCode2 = Double.toString(geopointBLat / 1E6) + "," + Double.toString(geopointBLng / 1E6);
	//System.out.println("Parsing 2 values");
	//System.out.println("Building query from data");
	String googleKML = kmlBuilder(geoCode1, geoCode2);
	//System.out.println("Connecting to " + googleKML);
	try {
	    URL url = new URL(googleKML);
	    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
	    while ((inputLine = in.readLine()) != null) {
		System.out.println(inputLine);
		receivedLine = inputLine;
		if (inputLine.contains("<![CDATA[Distance:")) {
		    tempString = inputLine.substring(inputLine.indexOf("<name>") + 6, inputLine.indexOf("</name>"));
		    startEndAddresses = tempString.split(" to ");
		    tempString = inputLine.substring(inputLine.indexOf("<![CDATA[Distance:") + 19, inputLine.lastIndexOf("&#160;") + 8);
		    tempString = tempString.replace("&#160;", "");
		    rawDistance = tempString;
		    //System.out.println("Your trip is estimated at " + rawDistance + " by car.");
		    //System.out.println("Start Location: " + startEndAddresses[0] + " (" + geoCode1 + ")");
		    startAddress = startEndAddresses[0];
		    //System.out.println("End Location: " + startEndAddresses[1] + " (" + geoCode2 + ")");
		    endAddress = startEndAddresses[1];
		    tempString = inputLine.substring(inputLine.indexOf("<LineString><coordinates>")+25, inputLine.indexOf(" </coordinates></LineString>"));
		    kmlPoints = tempString.replace(",0.000000", "");
		    kmlPointsArray = kmlPoints.split(" "); 
		    return "Start Location: " + startEndAddresses[0] + " (" + geoCode1 + ")" + "\nEnd Location: " + startEndAddresses[1] + " (" + geoCode2 + ")";
		}
	    }
	} catch (Exception e) {
	    e.printStackTrace();
	    return "error";
	}
	return "error";
    }

    public String kmlBuilder(String start, String end) {
	return kmlURL + kmlFROM + start + kmlTO + end + kmlOUTPUT;
    }

    public ArrayList<GeoPoint> getRoutePoints(){
	//GeoPoint[] geoPoints = new GeoPoint[kmlPointsArray.length];
	ArrayList<GeoPoint> markers = new ArrayList<GeoPoint>();
	//    	for(int i=0;i<kmlPointsArray.length;i++){
	//    		tempPoint = kmlPointsArray[i].split(",");
	//    		geoPoints[i] = new GeoPoint((int)(Double.parseDouble(tempPoint[1]) * 1E6), (int)(Double.parseDouble(tempPoint[0]) * 1E6));
	//    	}
	for(int i=0;i<kmlPointsArray.length;i++){
	    tempPoint = kmlPointsArray[i].split(",");
	    markers.add(new GeoPoint((int)(Double.parseDouble(tempPoint[1]) * 1E6), (int)(Double.parseDouble(tempPoint[0]) * 1E6)));
	}

	//return geoPoints;
	return markers;

    }
    /**
	 * @return the rawDistance
	 */
	public String getRawDistance() {
		return rawDistance;
	}
}
